package com.handong.handserialprogram.module.choosering;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.model.CriminalModel;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.LatLngEntity;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.module.setring.SetRingPresenter;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *  加入不是本机的任务选择脚环
 * Created by userKey on 2017/8/13.
 */
public class ChooseRingPresenter extends BasePresenter<ChooseRingActivity> {

    private static final String TAG = SetRingPresenter.class.getSimpleName();

    private SerialPortUtil mSerialPortUtil;
    private CopyOnWriteArrayList<FootRingNewEntity> mRingList;
    private CopyOnWriteArrayList<FootRingNewEntity> logoutFR;
    private Vector<PersonEntity> criminalList;
    private boolean isLogoutAll=false;
    private boolean mIsUploadSuccess = false;
    //private boolean mIsUploadSuccess = false;

    public ChooseRingPresenter(BaseView view) {
        super(view);
        logoutFR=new CopyOnWriteArrayList<>();


    }

    protected void scanAroundFootRing() {
        EventBusUtil.register(this);
        mSerialPortUtil = SerialPortUtil.getInstance(mView);
        mSerialPortUtil.openSerialPortToReadData();
        mSerialPortUtil.updateWorking(false);
    }

    /**
     * 激活脚环
     */
    public void activateFootRing(String id) {

        FootRingNewEntity entity= FootRingNewUtil.findFootRingById(mRingList,id);
        if (entity!=null&&entity.isNormalWork()) {
            AppUtil.showShortToast(this.mView, "脚环已激活");
            return;
        }

        mView.showLoadDialog("脚环激活中...");
        this.mSerialPortUtil.activateFootRing(id);
    }

    /**
     * 休眠脚环
     */
    public void logoutFootRing(String id) {
        this.mView.showLoadDialog("脚环休眠中...");
        this.mSerialPortUtil.logoutFootRing(id);
    }

    public void logoutAllFootRing() {
        if(!logoutFR.isEmpty()&&mSerialPortUtil!=null){
            isLogoutAll=true;
            String ringId=logoutFR.get(0).getRingID();
            this.mView.showLoadDialog("正在休眠脚环："+ringId);
            this.mSerialPortUtil.logoutFootRing(ringId);
        }
    }


    protected void forceExit(String id) {
        FootRingNewEntity entity= FootRingNewUtil.findFootRingById(mRingList,id);
        if(entity!=null){
            entity.setNormalWork(false);
        }
    }

    /**
     * 接收脚环列表
     * @param list
     */
    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveFootRing(CopyOnWriteArrayList<FootRingNewEntity> list) {
        if (this.mRingList == null) {
            this.mRingList = list;
        }

        logoutFR.clear();
        for (FootRingNewEntity entity:mRingList) {
            if(entity.isMyBingding()&&entity.isNormalWork()){
                logoutFR.add(entity);
            }
        }

        this.mView.showFootRingList(list);
    }

    /**
     * 接收脚环处理信息
     * @param response
     */
    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        switch (response.getResponseCode()) {
            case RingResponse.ACTIVATE_ORDER:
                if (response.isSuccess()) {
                    mView.showLoadDialog("脚环正在连接GPS和网络...");
                } else {
                    mView.activateRingError(response.getRingID());
                }
                break;

            case RingResponse.INIT_2GNET_SUCCESS:
                if (response.isSuccess()) {
                    mView.activateRingSuccess();
                } else {
                    mView.activateRingError(response.getRingID());
                }
                break;

            case RingResponse.LOGOUT_ORDER:
                if (response.isSuccess()) {
                    if(!logoutFR.isEmpty()&&isLogoutAll){
                        logoutFR.remove(FootRingNewUtil.findFootRingById(logoutFR,response.getRingID()));
                        logoutAllFootRing();
                        if(logoutFR.isEmpty()){
                            isLogoutAll=false;
                            mView.dismissLoadingDialog();
                            mView.logoutSuccess(response.getRingID());
                        }
                        break;
                    }else{
                        isLogoutAll=false;
                        mView.dismissLoadingDialog();
                        mView.logoutSuccess(response.getRingID());
                    }
                } else {
                    isLogoutAll=false;
                    mView.dismissLoadingDialog();
                    mView.logoutFail(response.getRingID());
                }
                break;

            case RingResponse.SIM_ERROR:
                mView.simInitError(response.getRingID());
                break;
            default:
                return;
        }
    }

    /**
     * 上传绑定脚环信息
     */
    public void uploadBingRingInfo(String missID) {
        RequestParams params = new RequestParams("visit", "BindAgain");
        params.put("missId", missID);
        params.put("pPhone", SPUtil.getStringValue(SPUtil.PHONE_NAME));
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
//        params.put("ring", mRingList.get(0).getRingID());
        //TODO 要修改一对多
        String ids = "";
        for (FootRingNewEntity item : mRingList) {
            if (item.isMyBingding())
            {
                ids+=item.getRingID()+",";
            }
        }
        params.put("ring",ids);

        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.bindPersonInfoFail("服务器无响应");
                JLog.d(TAG, "Upload Result:" + throwable.toString());
                mIsUploadSuccess = false;
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, "Upload Result:" + s);
                if (!TextUtils.isEmpty(s.toString())) {
                    try {
                        JSONObject obj = new JSONObject(s);
                        if (obj.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
                            mIsUploadSuccess = true;
                            mView.bindPersonInfoSuccess("绑定成功");
                        } else {
                            mView.bindPersonInfoFail(obj.getString(HttpConstant.FAIL_REASON));
                            mIsUploadSuccess = false;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mView.bindPersonInfoFail("服务器无响应");
                        mIsUploadSuccess = false;
                    }
                }
            }
        });
    }



    protected String checkErrorFootring()
    {
        CopyOnWriteArrayList<FootRingNewEntity> mRingListTemp=new CopyOnWriteArrayList<FootRingNewEntity>();
        StringBuilder result= new StringBuilder();
        //CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        mSerialPortUtil.SetReadRunnableIsStop(true);//首先停止recycle
        //String[] bindErrorFoot=new String[activity.getmRingList().size()];
        byte j=0;
        for (int i=0;i<mRingList.size();i++) {
            FootRingNewEntity entity=mRingList.get(i);
            if(entity.isMyBingding()){

                entity.setUwbCycle(j);
                entity.setIsActive(32);
                j++;
                for (int z=0;z<2;z++) {
                    mSerialPortUtil.sendFootRing(entity);
//                    entity.setReceiveData(false);
                    mSerialPortUtil.mReadRunnable.ringId = entity.getRingID();
                    long startTime = System.currentTimeMillis();
                    while (!mSerialPortUtil.mReadRunnable.DoWork(entity.getRingID(), false)) {
                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (System.currentTimeMillis() - startTime >= 500) {
                            mSerialPortUtil.mReadRunnable.DoWork(entity.getRingID(), true);
                            //isReceive=false;
                            break;
                        }
                    }
                    if (entity.isReceiveData())
                    {
                        break;
                    }
                }
                if (!entity.isReceiveData())
                {
                    //没有收到数据
                    if (!result.toString().equals(""))
                    {
                        result.append(",");
                    }
                    result.append(entity.getRingID());

                }
                else{
                    mRingListTemp.add(entity);
                }
                //showActivateGuideView(mRingAdapter.getView(i));
                //return;
            }
            else{
                mRingListTemp.add(entity);
            }

        }
        if (!result.toString().equals(""))
        {
            mSerialPortUtil.mReadRunnable.ringId = "";
            FootRingNewEntity entity=new FootRingNewEntity();
            entity.setPhoneSend(false);
            entity.setIsActive(0);
            mSerialPortUtil.sendFootRing(entity);
            mSerialPortUtil.setRingList(mRingListTemp);
            mRingList=mRingListTemp;
            mView.showFootRingList(mRingList);
            mSerialPortUtil.SetReadRunnableIsStop(false);//恢复recycle
        }

        return result.toString();
    }

    /**
     * 加入任务
     */
    public void requestJoinMiss(String missID) {
        RequestParams params = new RequestParams("visit", "JoinBind");
        params.put("missId", missID);
        params.put("pPhone", SPUtil.getStringValue(SPUtil.PHONE_NAME));
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
//        params.put("ring", mRingList.get(0).getRingID());//TODO 要修改

        String ids = "";
        for (FootRingNewEntity item : mRingList) {
            if (item.isMyBingding())
            {
                ids+=item.getRingID()+";"+(item.getCriminalId().equals("")?" ":item.getCriminalId())+",";
                //ids+=item.getRingID()+",";
            }
        }
        if (ids.contains(","))
        {
            ids=ids.substring(0, ids.length()-1);
        }
        params.put("ring",ids);

        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.joinMissionFail("服务器无响应");
                JLog.d(TAG, "Upload Result:" + throwable.toString());
                mIsUploadSuccess = false;
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, "Upload Result:" + s);
                if (!TextUtils.isEmpty(s.toString())) {
                    try {
                        JSONObject obj = new JSONObject(s);
                        if (obj.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
                            mIsUploadSuccess = true;
                            mView.bindPersonInfoSuccess("加入任务成功");
                        } else {
                            mView.joinMissionFail(obj.getString(HttpConstant.FAIL_REASON));
                            mIsUploadSuccess = false;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mView.joinMissionFail("服务器无响应");
                        mIsUploadSuccess = false;
                    }
                }
            }
        });
    }
    protected void closeSerialPort()
    {
        if (mSerialPortUtil!=null)
        {
            mSerialPortUtil.closeSerialPort();
        }
    }
    /**
     * 是否有我绑定的脚环
     */
    public boolean hasMyBingding() {
        for (FootRingNewEntity footRingEntity:mRingList) {
            if(footRingEntity.isMyBingding()){
                return true;
            }
        }
        return false;
    }



    /**
     * 获取可绑定脚环的位置
     */
    public int getNoBingdingPosstion(){
        for (int i=0;i<mRingList.size();i++) {
            FootRingNewEntity entity=mRingList.get(i);
            if(!entity.isBingding()){
                return i;
            }
        }
        return -1;
    }

    /**
     * 是否有可绑定的脚环
     */
    public boolean hasCanBingDing(){
       if(!hasMyBingding()&&getNoBingdingPosstion()!=-1){
           return true;
       }
       return false;
    }





    public boolean isCanExit() {

        if (mIsUploadSuccess) {
            return true;
        }
        if (mRingList == null || mRingList.isEmpty()) {
            return true;
        }
        if(logoutFR.size()>0){
            mView.showExitAllDialog();
            return false;
        }
       /* StringBuffer buffer=new StringBuffer();
        for (FootRingNewEntity footRingEntity:mRingList) {
            if (footRingEntity.isNormalWork()) {
                buffer.append(footRingEntity.getRingID()+";");
            }
        }
        if(!TextUtils.isEmpty(buffer.toString())){
            String st=buffer.substring(0,buffer.length()-1);
            mView.showExitDialog(st);
            return false;
        }*/

        return true;
    }



    @Override
    protected void exit() {
        AsyncHttpUtil.cancelSpecifiedRequest(mView);
        EventBusUtil.unRegister(this);
        if (!mIsUploadSuccess) {
            this.mSerialPortUtil.closeSerialPort();
        }
        super.exit();
    }
}
